package com.gaswell.config;

import org.apache.tomcat.util.threads.ThreadPoolExecutor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

@Configuration
@EnableAsync
public class AsyncConfig implements AsyncConfigurer {

    public ThreadPoolTaskExecutor getAsyncExecutor(String name) {
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        // 核心线程数：线程池创建的时候初始化的线程数
        taskExecutor.setCorePoolSize(16);
        // 最大线程数：线程池最大的线程数，只有缓冲队列满了之后才会申请超过核心线程数的线程
        taskExecutor.setMaxPoolSize(32);
        // 缓冲队列：用来缓冲执行任务的队列
        taskExecutor.setQueueCapacity(100);
        // 线程池关闭：等待所有任务都完成再关闭
        taskExecutor.setWaitForTasksToCompleteOnShutdown(true);
        // 等待时间：等待5秒后强制停止
        taskExecutor.setAwaitTerminationSeconds(5);
        // 允许空闲时间：超过核心线程之外的线程到达60秒后会被销毁
        taskExecutor.setKeepAliveSeconds(60);
        // 线程名称前缀
        taskExecutor.setThreadNamePrefix(name);
//         若是被拒绝，则直接执行，不通过线程进行执行
        taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());

        taskExecutor.initialize();
        return taskExecutor;
    }


//    @Override
    @Bean(name = "threadPoolTaskExecutor")
    public ThreadPoolTaskExecutor getAsyncExecutor() {
        return getAsyncExecutor("threadpool1--");
    }


    @Bean(name = "threadPoolTaskExecutor_forqba01")
    public ThreadPoolTaskExecutor getAsyncExecutor2() {
        return getAsyncExecutor("threadpool2--");
    }

    @Bean(name = "threadPoolTaskExecutor_forqba01count")
    public ThreadPoolTaskExecutor getAsyncExecutor3() {
        return getAsyncExecutor("threadpool3--");
    }

    @Bean(name = "threadPoolTaskExecutor_forclearQba01Count")
    public ThreadPoolTaskExecutor getAsyncExecutor4() {
        return getAsyncExecutor("threadpool4--");
    }




}

